package com.atjyb.blog.controller;



import com.atjyb.blog.common.lang.Result;
import com.atjyb.blog.entity.Blog;
import com.atjyb.blog.service.BlogService;
import com.atjyb.blog.util.ShiroUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author：jyb
 * @since 2022-11-05
 */
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1")Integer currentPage){
        Page page=new Page(currentPage,5);
        IPage<Blog> blogIPage = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(blogIPage);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已被删除");
        return Result.success(blog);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){

        Blog tempBlog=null;

        //编辑
        if (blog.getId()!=null){
            tempBlog=blogService.getById(blog.getId());
            //只能编辑自己的位置
            Assert.isTrue(tempBlog.getUserId() == ShiroUtil.getProfile().getId(),"没有编辑权限");
        }else {
            //添加
            tempBlog=new Blog();
            tempBlog.setUserId(ShiroUtil.getProfile().getId());
            tempBlog.setCreated(LocalDateTime.now());
            tempBlog.setStatus(0);

        }

        BeanUtils.copyProperties(blog,tempBlog,"id","userId","created","status");
        blogService.saveOrUpdate(tempBlog);
        return Result.success(tempBlog);
    }
}
